﻿using Application.Dto;
using Application.IAppSrevices;
using AutoMapper;
using Domain.Entitys;
using Microsoft.AspNetCore.Mvc;

namespace UI.Controllers
{
    public class LoginController : Controller
    {
        private readonly IMapper mapper;
        private readonly IRolesService rolesService;
        private readonly IUserService userService;

        public LoginController(IUserService userService,IMapper mapper,IRolesService rolesService )
        {
            this.mapper = mapper;
            this.rolesService = rolesService;
            this.userService = userService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Login(UserLogin userLogin)
        {
            if (ModelState.IsValid)
            {
                User user = await userService.Login(userLogin);
                if (user == null)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    HttpContext.Session.SetString("UTrueName", user.UTrueName);
                    UR uR = userService.GetUR(user.UId);
                    HttpContext.Session.SetString("RolesName", uR.RolesName);
                    HttpContext.Session.SetString("RolesID", uR.RolesID.ToString());
                    return RedirectToAction("HomePage");
                }
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public IActionResult Hello()
        {
            return View();
        }

        public IActionResult HomePage()
        {
            string userName = HttpContext.Session.GetString("UTrueName");
            ViewBag.UserTrueName = userName;
            string roleName = HttpContext.Session.GetString("RolesName");
            ViewBag.RolesName = roleName;
            return View();
        }

        public IActionResult QX()
        {
            string roleName = HttpContext.Session.GetString("RolesID");
            return Json(rolesService.GetQX2(roleName));
        }
    }
}
